from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from .models import Department, Menu, MenuMeta, Role


class DepartmentSerializer(serializers.ModelSerializer):
    """部门序列化器"""
    children = serializers.SerializerMethodField()
    status_text = serializers.SerializerMethodField()

    class Meta:
        model = Department
        fields = '__all__'
        read_only_fields = ['id', 'create_time']

    def get_children(self, obj):
        """获取子部门"""
        children = obj.children.all().order_by('id')
        if children:
            return DepartmentSerializer(children, many=True).data
        return []

    def get_status_text(self, obj):
        """获取状态文本"""
        return obj.get_status_display()


class MenuMetaSerializer(serializers.ModelSerializer):
    """菜单元数据序列化器"""
    class Meta:
        model = MenuMeta
        fields = '__all__'

class MenuSerializer(serializers.ModelSerializer):
    """菜单序列化器"""
    parent = serializers.CharField(source='pid.name', read_only=True)
    meta = MenuMetaSerializer()
    children = serializers.SerializerMethodField()
    status_text = serializers.SerializerMethodField()
    type_text = serializers.SerializerMethodField()

    class Meta:
        model = Menu
        fields = '__all__'
        read_only_fields = ['id', 'create_time', 'update_time']

    def get_children(self, obj):
        """获取子菜单"""
        children = obj.children.all()
        if children:
            return MenuSerializer(children, many=True).data
        return []

    def get_status_text(self, obj):
        """获取状态文本"""
        return obj.get_status_display()

    def get_type_text(self, obj):
        """获取菜单类型文本"""
        return obj.get_type_display()

    def create(self, validated_data):
        """创建菜单及关联的元数据"""
        meta_data = validated_data.pop('meta')
        meta = MenuMeta.objects.create(**meta_data)
        menu = Menu.objects.create(meta=meta, **validated_data)
        return menu

    def update(self, instance, validated_data):
        """更新菜单及关联的元数据"""
        meta_data = validated_data.pop('meta', {})
        meta_serializer = self.fields['meta']
        meta_serializer.update(instance.meta, meta_data)
        return super().update(instance, validated_data)


class RoleSerializer(serializers.ModelSerializer):
    """角色序列化器"""
    permissions = serializers.PrimaryKeyRelatedField(
        queryset=Menu.objects.all(),
        many=True,
        required=False
    )
    status_text = serializers.SerializerMethodField()

    class Meta:
        model = Role
        fields = '__all__'
        read_only_fields = ['id', 'create_time']

    def get_status_text(self, obj):
        """获取状态文本"""
        return obj.get_status_display()
